
struct ListNode
{
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};

class Solution
{
public:
    ListNode *reverseBetween(ListNode *head, int m, int n)
    {
        if (m == n)
            return head;
        ListNode *low = head, *fast = head;
        ListNode *left_tail = nullptr;
        for (int i = 1; i < m || i < n; ++i)
        {
            if (i < m)
            {
                left_tail = low;
                low = low->next;
            }
            if (i < n)
                fast = fast->next;
        }
        ListNode *tmp_tail = low;
        ListNode *right_head = fast->next;
        auto *newHead = new ListNode(0);
        while (low != right_head)
        {
            ListNode *tmp = low;
            low = low->next;
            tmp->next = newHead->next;
            newHead->next = tmp;
        }
        if (left_tail)
            left_tail->next = newHead->next;
        else
            head = newHead->next;
        tmp_tail->next = right_head;
        if (m)
            return head;
        else
            return newHead->next;
    }
};